using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
using EIMS.Data;
using EIMS.Models;
using EIMS.Models.Enums;
using EIMS.Models.ViewModels;
using System.Security.Claims;

namespace EIMS.Controllers
{
    [Authorize]
    public class EmployeesController : Controller
    {
        private readonly ApplicationDbContext _context;

        public EmployeesController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Employees
        public async Task<IActionResult> Index(string searchString, int? departmentId, EmployeeStatus? status)
        {
            var employeesQuery = _context.Employees
                .Include(e => e.Department)
                .AsQueryable();

            // 搜索过滤
            if (!string.IsNullOrEmpty(searchString))
            {
                employeesQuery = employeesQuery.Where(e => 
                    e.Name.Contains(searchString) || 
                    e.EmployeeNumber.Contains(searchString) ||
                    e.PhoneNumber.Contains(searchString) ||
                    e.Email.Contains(searchString)
                );
            }

            // 部门过滤
            if (departmentId.HasValue)
            {
                employeesQuery = employeesQuery.Where(e => e.DepartmentId == departmentId);
            }

            // 状态过滤
            if (status.HasValue)
            {
                employeesQuery = employeesQuery.Where(e => e.Status == status);
            }

            // 为视图准备部门下拉列表数据
            ViewBag.DepartmentList = new SelectList(await _context.Departments.ToListAsync(), "Id", "Name", departmentId);
            
            // 将枚举转换为下拉列表选项
            ViewBag.StatusList = Enum.GetValues(typeof(EmployeeStatus))
                .Cast<EmployeeStatus>()
                .Select(e => new SelectListItem
                {
                    Value = ((int)e).ToString(),
                    Text = e.ToString(),
                    Selected = status.HasValue && status.Value == e
                })
                .ToList();

            // 把搜索条件放入ViewBag用于视图中保留搜索条件
            ViewBag.SearchString = searchString;
            ViewBag.DepartmentId = departmentId;
            ViewBag.Status = status;

            return View(await employeesQuery.ToListAsync());
        }

        // GET: Employees/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var employee = await _context.Employees
                .Include(e => e.Department)
                .Include(e => e.EmployeeHistories)
                    .ThenInclude(h => h.OldDepartment)
                .Include(e => e.EmployeeHistories)
                    .ThenInclude(h => h.NewDepartment)
                .FirstOrDefaultAsync(m => m.Id == id);
                
            if (employee == null)
            {
                return NotFound();
            }

            return View(employee);
        }

        // GET: Employees/Create
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> Create()
        {
            ViewData["DepartmentId"] = new SelectList(await _context.Departments.ToListAsync(), "Id", "Name");
            return View();
        }

        // POST: Employees/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> Create([Bind("Id,EmployeeNumber,Name,Gender,DateOfBirth,PhoneNumber,Email,Address,HireDate,Status,DepartmentId")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                // 获取用户ID
                string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
                if (string.IsNullOrEmpty(userId))
                {
                    ModelState.AddModelError(string.Empty, "无法获取用户信息，请重新登录");
                    ViewData["DepartmentId"] = new SelectList(await _context.Departments.ToListAsync(), "Id", "Name", employee.DepartmentId);
                    return View(employee);
                }

                // 设置创建时间
                employee.CreatedAt = DateTime.Now;
                
                // 保存员工信息
                _context.Add(employee);
                await _context.SaveChangesAsync();
                
                // 创建入职历史记录
                var history = new EmployeeHistory
                {
                    EmployeeId = employee.Id,
                    Type = HistoryType.Hire,
                    EffectiveDate = employee.HireDate,
                    NewDepartmentId = employee.DepartmentId,
                    Remarks = "新员工入职",
                    CreatedAt = DateTime.Now,
                    CreatedBy = userId
                };
                _context.EmployeeHistories.Add(history);
                await _context.SaveChangesAsync();
                
                TempData["SuccessMessage"] = "员工添加成功！";
                return RedirectToAction(nameof(Index));
            }
            
            ViewData["DepartmentId"] = new SelectList(await _context.Departments.ToListAsync(), "Id", "Name", employee.DepartmentId);
            return View(employee);
        }

        // GET: Employees/Edit/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var employee = await _context.Employees.FindAsync(id);
            if (employee == null)
            {
                return NotFound();
            }
            
            ViewData["DepartmentId"] = new SelectList(await _context.Departments.ToListAsync(), "Id", "Name", employee.DepartmentId);
            return View(employee);
        }

        // POST: Employees/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> Edit(int id, [Bind("Id,EmployeeNumber,Name,Gender,DateOfBirth,PhoneNumber,Email,Address,HireDate,Status,TerminationDate,DepartmentId,CreatedAt")] Employee employee)
        {
            if (id != employee.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                // 获取用户ID
                string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
                if (string.IsNullOrEmpty(userId))
                {
                    ModelState.AddModelError(string.Empty, "无法获取用户信息，请重新登录");
                    ViewData["DepartmentId"] = new SelectList(await _context.Departments.ToListAsync(), "Id", "Name", employee.DepartmentId);
                    return View(employee);
                }

                try
                {
                    // 获取当前员工信息以比较部门变化
                    var currentEmployee = await _context.Employees.AsNoTracking()
                        .FirstOrDefaultAsync(e => e.Id == id);
                        
                    if (currentEmployee == null)
                    {
                        return NotFound();
                    }
                    
                    // 设置更新时间
                    employee.UpdatedAt = DateTime.Now;
                    
                    // 更新员工记录
                    _context.Update(employee);
                    await _context.SaveChangesAsync();
                    
                    // 如果部门发生变化，则添加历史记录
                    if (currentEmployee.DepartmentId != employee.DepartmentId)
                    {
                        var history = new EmployeeHistory
                        {
                            EmployeeId = employee.Id,
                            Type = HistoryType.Transfer,
                            EffectiveDate = DateTime.Now.Date,
                            OldDepartmentId = currentEmployee.DepartmentId,
                            NewDepartmentId = employee.DepartmentId,
                            Remarks = "部门调动",
                            CreatedAt = DateTime.Now,
                            CreatedBy = userId
                        };
                        _context.EmployeeHistories.Add(history);
                        await _context.SaveChangesAsync();
                    }
                    
                    // 如果员工状态变为离职，且未设置离职日期，则自动设置为今天
                    if (employee.Status == EmployeeStatus.Terminated && 
                        (!currentEmployee.TerminationDate.HasValue || currentEmployee.Status != EmployeeStatus.Terminated))
                    {
                        if (!employee.TerminationDate.HasValue)
                        {
                            employee.TerminationDate = DateTime.Now.Date;
                            _context.Update(employee);
                            await _context.SaveChangesAsync();
                        }
                        
                        // 添加离职历史记录
                        var history = new EmployeeHistory
                        {
                            EmployeeId = employee.Id,
                            Type = HistoryType.Termination,
                            EffectiveDate = employee.TerminationDate.Value,
                            OldDepartmentId = employee.DepartmentId,
                            Remarks = "员工离职",
                            CreatedAt = DateTime.Now,
                            CreatedBy = userId
                        };
                        _context.EmployeeHistories.Add(history);
                        await _context.SaveChangesAsync();
                    }
                    
                    TempData["SuccessMessage"] = "员工信息更新成功！";
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EmployeeExists(employee.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            
            ViewData["DepartmentId"] = new SelectList(await _context.Departments.ToListAsync(), "Id", "Name", employee.DepartmentId);
            return View(employee);
        }
        
        // GET: Employees/AddHistory/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> AddHistory(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var employee = await _context.Employees
                .Include(e => e.Department)
                .FirstOrDefaultAsync(m => m.Id == id);
                
            if (employee == null)
            {
                return NotFound();
            }
            
            var historyViewModel = new EmployeeHistoryViewModel
            {
                EmployeeId = employee.Id,
                EmployeeName = employee.Name,
                EffectiveDate = DateTime.Now.Date,
                CurrentDepartmentId = employee.DepartmentId,
                CurrentDepartmentName = employee.Department?.Name ?? string.Empty
            };
            
            ViewData["DepartmentId"] = new SelectList(await _context.Departments.ToListAsync(), "Id", "Name");
            ViewData["HistoryTypes"] = new SelectList(Enum.GetValues(typeof(HistoryType))
                .Cast<HistoryType>()
                .Select(e => new { Id = (int)e, Name = e.ToString() }),
                "Id", "Name");
                
            return View(historyViewModel);
        }
        
        // POST: Employees/AddHistory
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> AddHistory(EmployeeHistoryViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                // 获取用户ID
                string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
                if (string.IsNullOrEmpty(userId))
                {
                    ModelState.AddModelError(string.Empty, "无法获取用户信息，请重新登录");
                    
                    var employee = await _context.Employees
                        .Include(e => e.Department)
                        .FirstOrDefaultAsync(m => m.Id == viewModel.EmployeeId);
                        
                    if (employee != null)
                    {
                        viewModel.EmployeeName = employee.Name;
                        viewModel.CurrentDepartmentId = employee.DepartmentId;
                        viewModel.CurrentDepartmentName = employee.Department?.Name ?? string.Empty;
                    }
                    
                    ViewData["DepartmentId"] = new SelectList(await _context.Departments.ToListAsync(), "Id", "Name");
                    ViewData["HistoryTypes"] = new SelectList(Enum.GetValues(typeof(HistoryType))
                        .Cast<HistoryType>()
                        .Select(e => new { Id = (int)e, Name = e.ToString() }),
                        "Id", "Name");
                    
                    return View(viewModel);
                }

                var history = new EmployeeHistory
                {
                    EmployeeId = viewModel.EmployeeId,
                    Type = viewModel.Type,
                    EffectiveDate = viewModel.EffectiveDate,
                    OldDepartmentId = viewModel.OldDepartmentId,
                    NewDepartmentId = viewModel.NewDepartmentId,
                    Remarks = viewModel.Remarks ?? string.Empty,
                    CreatedAt = DateTime.Now,
                    CreatedBy = userId
                };
                
                _context.Add(history);
                
                // 如果是部门调动，同时更新员工的部门
                if (viewModel.Type == HistoryType.Transfer && viewModel.NewDepartmentId.HasValue)
                {
                    var employeeToUpdate = await _context.Employees.FindAsync(viewModel.EmployeeId);
                    if (employeeToUpdate != null)
                    {
                        employeeToUpdate.DepartmentId = viewModel.NewDepartmentId;
                        employeeToUpdate.UpdatedAt = DateTime.Now;
                        _context.Update(employeeToUpdate);
                    }
                }
                
                await _context.SaveChangesAsync();
                TempData["SuccessMessage"] = "员工历史记录添加成功！";
                return RedirectToAction(nameof(Details), new { id = viewModel.EmployeeId });
            }
            
            var employeeData = await _context.Employees
                .Include(e => e.Department)
                .FirstOrDefaultAsync(m => m.Id == viewModel.EmployeeId);
                
            if (employeeData != null)
            {
                viewModel.EmployeeName = employeeData.Name;
                viewModel.CurrentDepartmentId = employeeData.DepartmentId;
                viewModel.CurrentDepartmentName = employeeData.Department?.Name ?? string.Empty;
            }
            
            ViewData["DepartmentId"] = new SelectList(await _context.Departments.ToListAsync(), "Id", "Name");
            ViewData["HistoryTypes"] = new SelectList(Enum.GetValues(typeof(HistoryType))
                .Cast<HistoryType>()
                .Select(e => new { Id = (int)e, Name = e.ToString() }),
                "Id", "Name");
                
            return View(viewModel);
        }

        // GET: Employees/Delete/5
        [Authorize(Roles = "Administrator")]
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var employee = await _context.Employees
                .Include(e => e.Department)
                .FirstOrDefaultAsync(m => m.Id == id);
                
            if (employee == null)
            {
                return NotFound();
            }

            return View(employee);
        }

        // POST: Employees/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator")]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var employee = await _context.Employees.FindAsync(id);
            
            if (employee == null)
            {
                return NotFound();
            }
            
            // 删除员工相关的历史记录
            var histories = await _context.EmployeeHistories.Where(h => h.EmployeeId == id).ToListAsync();
            _context.EmployeeHistories.RemoveRange(histories);
            
            // 删除员工记录
            _context.Employees.Remove(employee);
            await _context.SaveChangesAsync();
            
            TempData["SuccessMessage"] = "员工记录已删除！";
            return RedirectToAction(nameof(Index));
        }

        private bool EmployeeExists(int id)
        {
            return _context.Employees.Any(e => e.Id == id);
        }
    }
}